package com.peanut.wapp.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.peanut.wapp.controller.res.PageResult;
import com.peanut.wapp.controller.resBean.RUserInfoBean;
import com.peanut.wapp.model.UserInfoBean;
import com.peanut.wapp.persist.UserDao;
import com.peanut.wapp.service.UserService;
import com.peanut.wapp.service.exception.ServiceException;
import com.peanut.wapp.util.AppTextUtil;
import com.peanut.wapp.util.DateTimeUtil;

@Service
public class UserServiceImpl implements UserService {
				
	@Autowired
	UserDao userImpl;

	@Override
	public boolean submitInfo(String name, String phone, String host) {
		UserInfoBean user = userImpl.selectOneByPhone(phone);
		if(user!= null) {
			throw new ServiceException("object_is_exist", "手机号");
		}
		
		user = new UserInfoBean();
		user.setUid(AppTextUtil.getPrimaryKey());
		user.setPhoneNum(phone);
		user.setUserName(name);
		user.setHost(host);
		return userImpl.insert(user) > 0;
	}

	@Override
	public PageResult<RUserInfoBean> getList(int start, int pageSize) {
		PageResult<RUserInfoBean> result = new PageResult<RUserInfoBean>();
		int count = userImpl.selectCount();
		List<UserInfoBean> resList = userImpl.selectList(start, pageSize);
		List<RUserInfoBean> resData = new ArrayList<>();
		for(UserInfoBean co : resList) {
			RUserInfoBean rc = new RUserInfoBean();
			rc.setUid(co.getUid());
			rc.setPhoneNum(co.getPhoneNum());
			rc.setState(co.getState());
			rc.setUserName(co.getUserName());
			rc.setHost(co.getHost());
			rc.setCreateTime(co.getCreateTime().getTime());
			rc.setCreateTimeStr(DateTimeUtil.formatTimestamp(rc.getCreateTime()/1000, null));
			resData.add(rc);
		}
		result.setCount(count);
		result.setData(resData);
		return result;
	}

	@Override
	public boolean handle(String uid) {
		UserInfoBean user = userImpl.selectOneById(uid);
		if(user == null) {
			throw new ServiceException("object_is_exist", "用户");
		}
		user.setState(1);
		return userImpl.update(user) > 0;
	}
}
